# -*- coding: utf-8 -*-

from aws import Aws, AwsServiceResource
import datetime

"""
key
s3://bucket/src/2016/10/24
"""
class AwsS3(AwsServiceResource):

    def _init(self):
        super(AwsS3, self)._init('s3')
        # self._cfg = cfg
        # self._bucket_name = self._cfg.get('bucket_name')
        self._bucket_name = self._cfg.get('bucket_name')
        self._source = self._cfg.get('source')
        self._bucket = self.get_bucket()

    def get_bucket(self):
        bucket = None
        try:
            bucket = self.resource.create_bucket(Bucket=self._bucket_name, CreateBucketConfiguration=
                                            {'LocationConstraint': 'cn-north-1'})

        except Exception as e:
            if e.message.find('BucketAlreadyOwnedByYou') > -1 and self._cfg.get('source'):
                bucket = self.resource.Bucket(self._bucket_name)
            if not bucket:
                raise e
        return bucket

    def get_all_buckets(self):
        return self.resource.buckets

    def save(self, file_name, file_content):
        file_key = self.__build_file_key(file_name)
        try:
            self._bucket.put_object(
                                    Body=file_content,
                                    Bucket=self._bucket_name,
                                    Key=file_key
                                    )
        except Exception as e:
            raise e

    def save_with_configuration(self):
        bucket_configuration = self.resource.BucketNotification(self._bucket_name)


    def __build_file_key(self, file_name):
        origin_key = 'src/'
        origin_key = origin_key + self._source + '/'
        time = datetime.datetime.now()
        origin_key = origin_key + str(time.year) + '/' + str(time.month) + '/' + str(time.day) + '/' + file_name
        return origin_key